import { useState, useRef } from 'react';

const usePos = (init_page=5) => {
    const [curpage, setCurpage] = useState(0);
    const [page, setPage] = useState(init_page);
    const [curpos, curPos] = useState(null);
    const [pos, setPos] = useState(null);

    const hrestore = () => {
        if (!curpos) {
            return;
        }

        let num = 0;

        const id = setInterval(() => {
            num += 1;
            if (num >= 6) {
                clearInterval(id);
                curPos(null);
                return;
            }

            const cp = document.getElementById(curpos);
            if (!cp) {
                return;
            }

            clearInterval(id);
            curPos(null);

            window.scrollTo({
                left: 0,
                top: pos,
                behavior: "smooth",
            });
        }, 100);
    };

    const hcur = (v) => {
        curPos(v);
        setPos(window.pageYOffset);
    };

    return {
        curpage: curpage,
        setCurpage: setCurpage,

        page: page,
        setPage: setPage,

        setPos: hcur,
        restorePos: hrestore,
    };
};

const useRow = () => {
    const [pos, setPos] = useState(null);
    const gref = useRef(null);

    const hrestore = () => {
        const curpos = parseInt(pos, 10);
        if (!curpos) {
            return;
        }

        if (curpos < 10) {
            return;
        }

        let num = 0;

        const id = setInterval(() => {
            num += 1;
            if (num >= 6) {
                clearInterval(id);
                return;
            }

            if (!gref.current) {
                return;
            }

            clearInterval(id);

            gref.current.scrollToRow(curpos - 1);

        }, 100);
    };

    return {
        gref: gref,
        setPos: setPos,
        restorePos: hrestore,
    };
};

export {useRow, usePos};
